import React, {createContext, ReactNode, useContext, useEffect, useState} from 'react';

type ThemeType = 'light' | 'dark';

interface ThemeContextValue {
    theme: ThemeType;
    toggleTheme: () => void;
}


// eslint-disable-next-line react-refresh/only-export-components
export const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);

export const ThemeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
    const [theme, setTheme] = useState<ThemeType>('light');

    useEffect(() => {
        // 从 localStorage 获取保存的主题偏好
        const savedTheme = localStorage.getItem('theme') as ThemeType;
        if (savedTheme) {
            setTheme(savedTheme);
        } else {
            // 如果没有保存的主题偏好，根据系统偏好设置
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            setTheme(prefersDark ? 'dark' : 'light');
        }
    }, []);

    const toggleTheme = () => {
        const newTheme = theme === 'light' ? 'dark' : 'light';
        setTheme(newTheme);
        localStorage.setItem('theme', newTheme);
    };

    return (
        <ThemeContext.Provider value={{ theme, toggleTheme }}>
            {children}
        </ThemeContext.Provider>
    );
};

// eslint-disable-next-line react-refresh/only-export-components
export  const  useTheme = () => {
    const context = useContext(ThemeContext);
    if (!context) {
        throw new Error('useTheme must be used within a ThemeProvider');
    }
    return context;
};